package com.etime.shycourse.config;


import com.etime.shycourse.dto.CurrentUser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

/**
 * 工具类
 *
 * @author zw
 */
@Component
public class Tools {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 从redis缓存中获取当前登录的用户
     *
     * @param token 用户令牌
     * @return 当前登录用户的信息。如果返回null则表示用户没有登录或者登录过期
     */
    public CurrentUser getCurrentUserFromRedis(String token) {
        if (token == null || token.equals ("")) {
            return null;
        }
        CurrentUser user = null;
        if (stringRedisTemplate.hasKey (token)) {
            //从reids中获取用户登录信息
            String str = stringRedisTemplate.boundValueOps (token).get ();
            //重置过期时间（不重新设置redis过期时间）
            //stringRedisTemplate.boundValueOps (token).expire (30, TimeUnit.MINUTES);
            ObjectMapper om = new ObjectMapper ();
            try {
                user = om.readValue (str, CurrentUser.class);
            } catch (JsonProcessingException e) {
                e.printStackTrace ();
                user = null;
            }
        }
        return user;
    }

    /**
     * 根据用户id redis缓存删除
     * 成功返回 1
     * 失败返回 0
     */

    public Boolean deleteUserFromRedisByUserId(Integer userID) {
        // 加密key
        String key = DigestUtils.md5DigestAsHex (userID.toString ().getBytes ());
        if (stringRedisTemplate.hasKey (key)) {
            return stringRedisTemplate.delete (key);
        } else {
            return true;
        }
    }
}
